package whu.cn.whushare.ui.main.known;

import whu.cn.whushare.R;
import whu.cn.whushare.bean.User;
import whu.cn.whushare.common.Constants;
import whu.cn.whushare.net.DownloadParams;
import whu.cn.whushare.net.Downloader;
import whu.cn.whushare.ui.common.BaseActivity;
import whu.cn.whushare.ui.common.LoadingHelper;
import whu.cn.whushare.ui.main.known.adapter.CommentListAdapter;
import whu.cn.whushare.ui.main.known.bean.CommentWrapper;
import whu.cn.whushare.util.InputMethodUtils;
import whu.cn.whushare.util.SetOnClickUtil;
import whu.cn.whushare.util.Utils;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.androidplus.util.ViewMapping;
import com.androidplus.util.ViewMappingUtil;
import com.dd.processbutton.iml.ActionProcessButton;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;

/**
 * 类 名：CommentListActivity
 * 功 能：包含对评论的操作，如发布评论、取消评论等
 */
@ViewMapping(id = R.layout.activity_answer_comment)         //获取activity_answer_comment布局文件
public class CommentListActivity extends BaseActivity {
	@ViewMapping(id = R.id.publish)                         //获取“发布”按钮
	private ActionProcessButton mPublishAnswerBtn;
	@ViewMapping(id = R.id.comment_list)                    //获取“评论列表”
	private PullToRefreshListView mRefreshListView;
	@ViewMapping(id = R.id.comment_edit)                    //获取“评论编辑框”
	private EditText mCommentEdit;
	@ViewMapping(id = R.id.bottom)                          //获取“底部视图”
	private View mBottomLayout;
	@ViewMapping(id = R.id.cancel_reply)                    //获取“取消回复”文本框
	private TextView mCancelReplyTxt;
	private LoadingHelper mLoadingHelper;
	private CommentListAdapter mAdapter;
	private List<CommentWrapper> mCommentWrappers = new ArrayList<>();

	private String mAnswerId;
	private String mQuestionId;

	private static final String INTENT_EXTRA_ANSWER_ID = "answerId";
	private long mReplyId = -1;

    //获取跳转到当前activity的intent信息，向intent中添加回答id和问题id
	public static Intent getStartIntent(Context context, String questionId, String answerId) {
		Intent i = new Intent(context, CommentListActivity.class);
		i.putExtra(INTENT_EXTRA_ANSWER_ID, answerId);
		i.putExtra(Constants.INTENT_EXTRA_QUESTION_ID, questionId);

		return i;
	}

	@Override
    //activity加载时调用该方法，主要完成初始化操作
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mAnswerId = getIntent().getStringExtra(INTENT_EXTRA_ANSWER_ID);
		mQuestionId = getIntent().getStringExtra(Constants.INTENT_EXTRA_QUESTION_ID);

		ViewMappingUtil.mapView(this, this);
		SetOnClickUtil.registerOnClick(this);
		initLoadingHelper();
		initRefreshView();
		requestComments();
	}

	private void initLoadingHelper() {
		mLoadingHelper = new LoadingHelper(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				requestComments();
			}
		});
		mLoadingHelper.onCreateView(LayoutInflater.from(this), mBottomLayout);
	}

    //对评论列表进行初始化，主要实现点击评论列表内容时可以对其进行评论的操作
	private void initRefreshView() {
		mAdapter = new CommentListAdapter(this, mCommentWrappers);
		mRefreshListView.setAdapter(mAdapter);
		mRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				User user = mAdapter.getItem(position - 1).user;
				mCommentEdit.setHint("回复 " + user.getId() + " 的评论 ：");
				mCommentEdit.setText("");
				mCancelReplyTxt.setVisibility(View.VISIBLE);
				mReplyId = mAdapter.getItem(position - 1).comment.id;
			}
		});

	}

    //请求评论
	private void requestComments() {
		mLoadingHelper.showLoadingView(false);
		Downloader.getInstance(this).getComments(mAnswerId, this);
	}

	@Override
    /**
     * 方法名：onClick(View v)
     * 功 能：根据发生点击事件的控件不同处理不同的点击事件
     *        控件为“发布”按钮时，发布回复内容
     *        控件为“取消回复”按钮时，取消用户的回复操作
     * 参 数：@param v - 发生点击事件的控件
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.publish:
			String content = mCommentEdit.getText().toString();
			if (TextUtils.isEmpty(content)) {
				toast(R.string.no_comment_content);
			} else {
				commitComment(content);
			}
			break;
		case R.id.cancel_reply:
			mCommentEdit.setHint(R.string.comment_hint);
			mCommentEdit.setText("");
			mCancelReplyTxt.setVisibility(View.GONE);   //隐藏“取消回复”按钮
			mReplyId = -1;
			break;
		default:
			break;
		}
	}

    //提交评论
	private void commitComment(String content) {
		mPublishAnswerBtn.setProgress(50);
		Downloader.getInstance(this).addComment(mQuestionId, mAnswerId, content, this);
	}

	@Override
    /**
     * 网络请求失败时调用该函数，
     * 当网络请求类型为“评论”时，显示重试页面
     * 当网络请求类型为“添加评论”时，进行提示
     * @param type - URL类型
     * @param response - 返回结果信息
     * @param obj -
     * @see whu.cn.whushare.net.NetResponseListener#onSuccess(whu.cn.whushare.net.DownloadParams.PARSING_TYPE, whu.cn.whushare.bean.Result<T>, java.lang.Object)
     */
	public void onFail(DownloadParams.PARSING_TYPE type, VolleyError error) {
		super.onFail(type, error);
		switch (type) {
		case COMMENTS:
			mLoadingHelper.showRetryView();
			toast(TextUtils.isEmpty(msg) ? getString(R.string.error_unknown) : msg);
			break;
		case ADD_COMMENT:
			if (TextUtils.isEmpty(msg)) {
				toast(msg);

			} else {
				toast(R.string.add_comment_fail);
			}
			mPublishAnswerBtn.setProgress(0);
			break;
		}
	}

	@Override
    /**
     * 网络请求成功时调用该函数
     * @param type - URL类型
     * @param response - 返回结果信息
     * @param obj -
     * @see whu.cn.whushare.net.NetResponseListener#onSuccess(whu.cn.whushare.net.DownloadParams.PARSING_TYPE, whu.cn.whushare.bean.Result<T>, java.lang.Object)
     */
	public <T> void onSuccess(DownloadParams.PARSING_TYPE type, T response, Object obj) {
		super.onSuccess(type, response, obj);
		switch (type) {
		case COMMENTS:
			mLoadingHelper.showContentView();
			List<CommentWrapper> temps = (List<CommentWrapper>) response;
			if (!Utils.isCollectionEmpty(temps)) {
				mCommentWrappers.clear();
				mCommentWrappers.addAll(temps);
			}
			break;
		case ADD_COMMENT:
			toast(msg);
			mPublishAnswerBtn.setProgress(100);
			InputMethodUtils.hideSoftInput(this);
			mCommentEdit.setText("");
			requestComments();
			break;
		}
	}
}
